import os
import shutil
from lib.xml_tool import XMLBox

class Config:
    def __init__(self,planSeq,log):
        self.log=log
        try:
            current_rootpath = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
            subconf = os.path.join(current_rootpath,os.path.pardir, 'dataset', planSeq, 'conf')
            xmlConfig = os.path.join(subconf, 'args.xml')
            curXML = XMLBox(xmlConfig)

            self.global_para = curXML.get_node_attrib_underpath('global_para')
            self.control = curXML.get_node_attrib_underpath('antopt/control')
            self.debug = (self.control['debug'] == 'True')

            self.subdir = curXML.get_node_attrib_underpath('antopt/subdir')
            self.pso = curXML.get_node_attrib_underpath('antopt/pso')
            self.expert = curXML.get_node_attrib_underpath('antopt/expert')
            self.mimo = curXML.get_node_attrib_underpath('antopt/mimo')
            self.modeltunning = curXML.get_node_attrib_underpath('antopt/modeltunning')
            self.fasttool = curXML.get_node_attrib_underpath('fasttool')
            self.CFG_CELLINFO_45G=curXML.get_nodes_attrib_alongpath('table/CFG_CELLINFO_45G')
            self.CFG_TRIANGLE_COVERAGE=curXML.get_nodes_attrib_alongpath('table/CFG_TRIANGLE_COVERAGE_Python')
            self.CGIGRID = curXML.get_nodes_attrib_alongpath('table/CGIGRID')


        except Exception as e:
            log.error('Error: {0}, please check configuration file!'.format(e))
            exit(1)

    def reCreateDir(self):
        self.log.info('初始化目录{}下临时目录'.format(self.global_para['workspace']))
        try:
            dirs=os.listdir(self.global_para['workspace'])
            for fileordir in dirs:
                tmpdir=os.path.join(self.global_para['workspace'], fileordir)
                if os.path.isdir(tmpdir):
                    if fileordir[0:3]!='lib' and fileordir[0:4]!='site' and fileordir[0:4]!='conf':
                        shutil.rmtree(tmpdir)

            for k, v in self.subdir.items():
                tmpdir = os.path.join(self.global_para['workspace'], v)
                if os.path.exists(tmpdir) == False:
                    os.mkdir(tmpdir)

        except Exception as e:
            self.log.error('create directory {0} failed! Please check dirctory!'.format(e))
            exit(1)
